package org.thief.frost.database;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.thief.frost.system.value.MenuDTO;

/**
 * @author zhengwei email: zw1987213@gmail.com blog:
 * @date 2013-5-17
 */
//@Repository
public class DatabaseManager<T> {
	
	protected final static String PAGE_SQL_PREFIX = "select * from(select m.*,rownum num from (";
	protected final static String PAGE_SQL_END = ") m where rownum<=?) where num>?";


	@Autowired
	private DataSource dataSource;
	@Autowired
	private JdbcTemplate jdbcTemplate;

	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
		System.out.println(this.jdbcTemplate + "-----");
	}

	/**
	 * String selectSql = "select * from test where name=:name"; paramBean 与
	 * sql语句中的名字对应
	 * 
	 * @param namedsql
	 * @param paramBean
	 * @return
	 */
	public int update(String namedsql, Object paramBean) {
		SqlParameterSource paramSource = new BeanPropertySqlParameterSource(
				paramBean);
		return this.jdbcTemplate.update(namedsql, paramSource);
	}

	/**
	 * 参数值应该与sql中的参数顺序对应
	 * 
	 * @param namedsql
	 * @param paramValue
	 * @return
	 */
	public int commonUpdate(String namedsql, Object... paramValue) {
		return this.jdbcTemplate.update(namedsql, paramValue);
	}

	public T getJavaBean(String namedSql, Class<T> retType,
			Object... paramValue) {
		RowMapper<T> rowMapper = new BeanPropertyRowMapper<T>(retType);
		return this.jdbcTemplate
				.queryForObject(namedSql, rowMapper, paramValue);
	}

	public List<T> getList(String namedSql, Class<T> retType,
			Object... paramValue) {
		RowMapper<T> rowMapper = new BeanPropertyRowMapper<T>(retType);
		return this.jdbcTemplate.query(namedSql, rowMapper, paramValue);
	}

	public List<T> getList(String sql, Class<T> returnType) {
		RowMapper<T> rowMapper = new BeanPropertyRowMapper<T>(returnType);
		return this.jdbcTemplate.query(sql, rowMapper);
	}

	public static void main(String[] args) {
		MenuDTO m = new MenuDTO();
		System.out.println(m instanceof MenuDTO);
	}
}
